<template>
  <div class="header-container">
    <div class="header-text">客服中心</div>
    <!-- 头像框 -->
    <el-avatar :src="userAvatar" size="large" shape="circle"></el-avatar>
    <div class="header-settings" @click="openSettings">
      <i class="el-icon-setting"></i>
    </div>

    <!-- 自定义弹框 -->
    <div v-if="settingsVisible" class="custom-dialog-overlay">
      <div class="custom-dialog">
        <div class="dialog-header">
          <span>账户设置</span>
          <i class="el-icon-close" @click="closeSettings"></i>
        </div>
        <div class="dialog-content">
          <div class="avatar-container">
            <img :src="userAvatar" alt="头像" class="avatar" @click="$refs.avatarInput.click()">
            <input ref="avatarInput" type="file" @change="handleAvatarChange" accept="image/*" class="avatar-input">
            <div class="upload-tip">点击更换头像</div>
          </div>
          <div class="user-info">
            <p>账号: {{ userTelephone }}</p>
            <p>昵称: {{ serviceNickname }}</p>
          </div>
        </div>
        <div class="dialog-footer">
          <el-button @click="closeSettings">取消</el-button>
          <el-button type="primary" @click="saveSettings">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
export default {
  data() {
    return {
      settingsVisible: false,
      userTelephone: '', 
      serviceNickname: '',
      serviceAvatar: '',
      selectedFile: null,
      saveLoading: false
    };
  },
  computed: {
    ...mapState(["user"]),
    userAvatar() {
      if (this.serviceAvatar) {
        // 如果有新上传的头像，则显示新头像
        return this.serviceAvatar;
      }
    }
  },
  methods: {
    ...mapMutations(['setUser']),
    //个人信息
    async fetchCustomerServiceInfo(){
      let resp = await this.customerServiceApi.customerServiceInfo();
      if (resp.code == 200) {
        const info = resp.data[0];
        this.userTelephone = info.userTelephone;
        this.serviceNickname = info.serviceNickname;
        this.serviceAvatar = info.serviceAvatar;
      }else{
        this.$message.error(resp.message);
      }
    },
    async openSettings() {
      await this.fetchCustomerServiceInfo();
      this.settingsVisible = true;
    },
    closeSettings() {
      this.fetchCustomerServiceInfo();
      this.settingsVisible = false;
      // 关闭时重置选择的文件
      this.selectedFile = null;
    },
    //头像
    handleAvatarChange(event) {
      const file = event.target.files[0];
      if (!file) return;
       // 检查文件大小和类型
      if (file.size > 10 * 1024 * 1024) {
        this.$message.error("文件过大,最大支持10MB");
        return;
      }
      const ext = file.name.substring(file.name.lastIndexOf("."));
      if (![".jpg", ".jpeg", ".png", ".gif"].includes(ext.toLowerCase())) {
        this.$message.error("不支持的文件类型");
        return;
      }
      // 预览选择的图片
      const reader = new FileReader();
      reader.onload = (e) => {
        this.serviceAvatar = e.target.result;
      };
      reader.readAsDataURL(file);
      this.selectedFile = file;
    },
    //保存
    async saveSettings() {
       if (!this.selectedFile) {
        this.settingsVisible = false;
        return;
      }
      this.settingsVisible = false;
      if (!this.user.userId) {
        this.$message.error("用户ID未获取,请重新登录");
        return;
      }
       // 创建 FormData 对象
      const formData = new FormData();
      formData.append('file', this.selectedFile);
      formData.append('customerId', this.user.userId);
      const resp = await this.customerServiceApi.uploadAvatar(formData);
      if(resp.code == 200){
        this.$message.success('头像上传成功');
        // 更新本地数据
        this.serviceAvatar = resp.data;
        const updatedUser = { ...this.user, serviceAvatar: resp.data }; 
        this.setUser(updatedUser); // 同步 Vuex
        this.settingsVisible = false;
      }else{
        this.$message.error("头像上传失败");
        this.saveLoading = false;
        this.selectedFile = null;
      }
    }
  },
  mounted(){
    this.fetchCustomerServiceInfo();
  }
};
</script>

<style scoped>
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 60px;
}

.header-text {
  color: #fff;
  text-align: left;
  line-height: 60px;
  font-size: 18px;
  font-weight: bold;
  margin-left: 20px;
}

.header-settings {
  cursor: pointer;
  color: #fff;
  padding: 10px;
  border-radius: 50%;
  transition: background-color 0.3s;
  margin-left: 1350px;
}

.header-settings:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

/* 自定义弹框样式 */
.custom-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.1); /* 调整透明度 */
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.custom-dialog {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  width: 400px;
  max-width: 90%;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.dialog-header i {
  cursor: pointer;
  font-size: 18px;
  color: #909399;
}

.dialog-content {
  padding: 20px;
}

.avatar-container {
  text-align: center;
  margin-bottom: 20px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  margin: 0 auto;
}

/* 隐藏文件选择框的默认提示文字 */
.avatar-input[type="file"]::-webkit-file-upload-button {
  display: none;
}

.avatar-input[type="file"] {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
  z-index: 2;
}
.avatar-input {
  display: none;
}

.avatar-container:hover .avatar-input {
  display: block;
}
.avatar-container {
  text-align: center;
  margin-bottom: 20px;
  position: relative;
  cursor: pointer;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  margin: 0 auto;
  transition: transform 0.3s ease;
}

.avatar:hover {
  transform: scale(1.05);
}
.user-info {
  margin-top: 20px;
}

.user-info p {
  margin: 10px 0;
  color: #333;
}

.dialog-footer {
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
</style>